import React, { memo, useState, forwardRef, useImperativeHandle, useEffect, useMemo } from 'react';
import type { MutableRefObject, ReactElement } from 'react';
import { Button, Modal, Form } from 'antd';

interface AddUnitDialogProps {
  formData: { current: any };
  onSubmit: any;
  ref: MutableRefObject<{ setOpen: any }>;
  children?: ReactElement;
}

const FormModal: React.FC<AddUnitDialogProps> = memo(
  forwardRef((props, ref) => {
    // console.log('FormModal子组件弹窗');
    const { formData, onSubmit, children } = props;

    const [open, setOpen] = useState(false);
    const [form] = Form.useForm();

    const { current } = formData;
    const type = Object.keys(current ?? {}).length;

    const initData = useMemo(() => ({}), []);

    useEffect(() => {
      if (type) {
        form.setFieldsValue(current);
      } else {
        form.resetFields();
      }
    }, [open]);

    const getFormData = async () => {
      const value = form.getFieldsValue();
      if (type) {
        value.id = formData.current.id;
        onSubmit(value);
      } else {
        onSubmit(value);
      }
      form.resetFields();
    };

    useImperativeHandle(ref, () => ({
      setOpen
    }));

    return (
      <Modal
        title={type ? '编辑' : '新建'}
        visible={open}
        onCancel={() => setOpen(false)}
        footer={[
          <Button key="cancel" onClick={() => setOpen(false)}>
            关闭
          </Button>,
          <Button key="submit" type="primary" onClick={getFormData}>
            提交
          </Button>
        ]}
      >
        <Form form={form} initialValues={initData} labelCol={{ span: 6 }}>
          {children}
        </Form>
      </Modal>
    );
  })
);

export default FormModal;
